<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const tipVisible = ref(false)
const tipMessage = ref('')
const lastMessage = ref('')
let es = null

async function fetchTip() {
  try {
    const res = await fetch('http://127.0.0.1:8000/ts/tip', {
      credentials: 'include',
    })
    if (!res.ok) return
    const data = await res.json()
    if (data && data.message) {
      if (data.message !== lastMessage.value) {
        lastMessage.value = data.message
        tipMessage.value = data.message
        tipVisible.value = true
        setTimeout(() => {
          tipVisible.value = false
        }, 20000) // 显示20秒
      }
    }
  } catch (e) {
    // 忽略错误
  }
}

onMounted(() => {
  fetchTip()
  // 优先使用SSE推送
  try {
    es = new EventSource('http://127.0.0.1:8000/ts/stream')
    es.onmessage = (evt) => {
      try {
        const data = JSON.parse(evt.data)
        if (data && data.message && data.message !== lastMessage.value) {
          lastMessage.value = data.message
          tipMessage.value = data.message
          tipVisible.value = true
          setTimeout(() => { tipVisible.value = false }, 20000)
        }
      } catch {}
    }
    es.onerror = () => {
      // SSE失败则继续使用轮询
    }
  } catch {}
})

onUnmounted(() => {
  if (es) {
    es.close()
    es = null
  }
})
</script>

<template>
  <transition name="tip-fade">
    <div v-if="tipVisible" class="tip-banner">
      <span>{{ tipMessage }}</span>
      <button class="tip-close" @click="tipVisible = false">×</button>
    </div>
  </transition>
  <router-view />
  
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.tip-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 12px 16px;
  background: #1f2937; /* slate-800 */
  color: #f9fafb; /* gray-50 */
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

.tip-close {
  appearance: none;
  border: none;
  background: transparent;
  color: #e5e7eb;
  font-size: 18px;
  cursor: pointer;
}

.tip-fade-enter-active, .tip-fade-leave-active { transition: opacity .25s; }
.tip-fade-enter-from, .tip-fade-leave-to { opacity: 0; }
</style>
